<template>
  <div class="notification-bell">
    <button class="bell-button" @click="togglePanel">
      <span class="bell-icon">🔔</span>
      <span v-if="unreadCount > 0" class="unread-badge">{{ unreadCount > 99 ? '99+' : unreadCount }}</span>
    </button>

    <!-- 通知下拉面板 -->
    <div v-if="isPanelOpen" class="notification-panel">
      <div class="panel-header">
        <h3>通知中心</h3>
        <button class="close-btn" @click="closePanel">×</button>
      </div>

      <div class="panel-content">
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="notifications.length === 0" class="empty-state">
          暂无通知
        </div>
        <div
          v-else
         v-for="notification in notifications"
        :key="notification.noticeGiven.id"
        :class="['notification-item', { unread: notification.noticeGiven.isRead === 0 }]"
        @click="viewNotification(notification)"
        >
          <div class="item-content">
           <h4 class="item-title">{{ notification.noticeDetail.title }}</h4>
          <p class="item-message">{{ notification.noticeDetail.content }}</p>
          <div class="item-meta">
            <span class="item-time">{{ formatTime(notification.noticeGiven.sendTime) }}</span>
            <span v-if="notification.noticeGiven.isRead === 0" class="unread-dot">●</span>
          </div>
          </div>
        </div>
      </div>

      <div class="panel-footer">
        <button class="view-all-btn" @click="goToNotificationCenter">
          查看全部
        </button>
        <button
          class="mark-all-read-btn"
          @click="markAllAsRead"
          :disabled="unreadCount === 0"
        >
          全部已读
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

// 替换为新的嵌套接口
interface NoticeGiven {
  id: number
  isRead: number
  sendTime: string
  oid: number | null
  uid: number | null
  nid: number
  mid: number | null
}

interface NoticeDetail {
  id: number
  title: string
  content: string
  senderType: number
  senderId: number
  receiverType: number
  createTime: string
  isUsing: boolean
}

interface Notification {
  noticeGiven: NoticeGiven
  noticeDetail: NoticeDetail
}
interface ListApiResponse {
  success: boolean
  data?: Notification[]
  message?: string
  notices?: Notification[]
}

interface CountApiResponse {
  success: boolean
  data?: number
  message?: string
  unreadCount?: number
}

interface BasicApiResponse {
  success: boolean
  message?: string
}

const router = useRouter()

// 响应式数据
const isPanelOpen = ref<boolean>(false)
const notifications = ref<Notification[]>([])
const unreadCount = ref<number>(0)
const loading = ref<boolean>(false)

// 获取通知列表
const fetchNotifications = async (): Promise<void> => {
  try {
    loading.value = true
    const token = localStorage.getItem('token')

    const response = await fetch('http://localhost:8080/ng/list', {
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const result: ListApiResponse = await response.json()
      console.log('API响应结果:', result)

      if (result.success) {

        // 后端返回的是 notices 字段，不是 data 字段
        if (Array.isArray(result.notices)) {
          notifications.value = result.notices
        } else if (Array.isArray(result.data)) {
          notifications.value = result.data
        } else {
          notifications.value = []
        }


        // 计算未读数量
        unreadCount.value = notifications.value.filter(n =>
          n.noticeGiven.isRead === 0
        ).length

        console.log('处理后的通知列表:', notifications.value)
        console.log('未读数量:', unreadCount.value)
      }
    } else {
      console.error('API请求失败:', response.status)
    }
  } catch (error) {
    console.error('获取通知失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取未读数量
const fetchUnreadCount = async (): Promise<void> => {
  try {
    const token = localStorage.getItem('token')

    const response = await fetch('http://localhost:8080/ng/unreadCount', {
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const result: CountApiResponse = await response.json()
      console.log('未读数量API响应:', result)

      if (result.success) {
        if (result.data !== undefined) {
          unreadCount.value = result.data
        } else if (result.unreadCount !== undefined) {
          unreadCount.value = result.unreadCount
        } else {
          unreadCount.value = 0
        }
      }
    }
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

// 标记为已读
const markAsRead = async (notification: Notification): Promise<void> => {
  if (notification.noticeGiven.isRead === 1) return

  try {
    const token = localStorage.getItem('token')

    const response = await fetch(`http://localhost:8080/ng/markAsRead?id=${notification.noticeGiven.id}`, {
      method: 'PUT',
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const result: BasicApiResponse = await response.json()
      if (result.success) {

        notification.noticeGiven.isRead = 1

        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
    }
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}
// 查看通知
const viewNotification = (notification: Notification): void => {
  markAsRead(notification)
  closePanel()
}

// 全部标记为已读
const markAllAsRead = async (): Promise<void> => {
  try {
    const token = localStorage.getItem('token')
    // 修改这里：使用嵌套路径
    const unreadNotifications = notifications.value.filter(n =>
      n.noticeGiven.isRead === 0
    )

    for (const notification of unreadNotifications) {
      // 修改这里：使用嵌套路径
      await fetch(`http://localhost:8080/ng/markAsRead?id=${notification.noticeGiven.id}`, {
        method: 'PUT',
        headers: {
          'token': token || '',
          'Content-Type': 'application/json'
        }
      })
    }

    // 修改这里：使用嵌套路径
    notifications.value.forEach(n => n.noticeGiven.isRead = 1)
    unreadCount.value = 0

  } catch (error) {
    console.error('全部标记已读失败:', error)
  }
}

// 跳转到通知中心
const goToNotificationCenter = (): void => {
  closePanel()
  router.push('/user-center/notification')
}

// 切换面板显示
const togglePanel = (): void => {
  isPanelOpen.value = !isPanelOpen.value
  if (isPanelOpen.value) {
    fetchNotifications()
  }
}

// 关闭面板
const closePanel = (): void => {
  isPanelOpen.value = false
}

// 点击外部关闭面板
const handleClickOutside = (event: MouseEvent): void => {
  const target = event.target as HTMLElement
  if (!target.closest('.notification-bell')) {
    closePanel()
  }
}

// 格式化时间
const formatTime = (timeString: string): string => {
  const date = new Date(timeString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

// 生命周期
onMounted(() => {
  fetchUnreadCount()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.notification-bell {
  position: relative;
  display: inline-block;
}

.bell-button {
  position: relative;
  background: linear-gradient(to right, #66BB6A, #43A047);
  border: none;
  border-radius: 8px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  font-family: '微软雅黑 Light', sans-serif;
}

.bell-button:hover {
  background: linear-gradient(to right, #558B2F, #388E3C);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

.unread-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #e74c3c;
  color: white;
  border-radius: 50%;
  min-width: 20px;
  height: 20px;
  font-size: 0.7rem;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  padding: 0 4px;
}

.notification-panel {
  position: absolute;
  top: 100%;
  right: 0;
  width: 380px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #A5D6A7;
  border-radius: 12px;
  box-shadow:
    0 8px 16px rgba(0, 0, 0, 0.1),
    inset 0 0 10px rgba(129, 199, 132, 0.2);
  z-index: 1000;
  margin-top: 10px;
  backdrop-filter: blur(10px);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #E8F5E8;
}

.panel-header h3 {
  margin: 0;
  color: #2E7D32;
  font-size: 1.1rem;
  font-family: '微软雅黑 Light', sans-serif;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #66BB6A;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.close-btn:hover {
  background: #E8F5E8;
  color: #2E7D32;
}

.panel-content {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  padding: 15px 20px;
  border-bottom: 1px solid #F1F8E9;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.notification-item:hover {
  background-color: #F1F8E9;
}

.notification-item.unread {
  background-color: #E8F5E8;
  border-left: 4px solid #4CAF50;
}

.item-content h4 {
  margin: 0 0 5px 0;
  color: #2E7D32;
  font-size: 0.95rem;
  font-family: '微软雅黑 Light', sans-serif;
}

.item-message {
  margin: 0 0 8px 0;
  color: #558B2F;
  font-size: 0.85rem;
  line-height: 1.4;
  font-family: '微软雅黑 Light', sans-serif;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-time {
  color: #81C784;
  font-size: 0.8rem;
  font-family: '微软雅黑 Light', sans-serif;
}

.unread-dot {
  color: #4CAF50;
  font-size: 0.8rem;
}

.loading, .empty-state {
  padding: 30px 20px;
  text-align: center;
  color: #81C784;
  font-family: '微软雅黑 Light', sans-serif;
}

.panel-footer {
  display: flex;
  justify-content: space-between;
  padding: 15px 20px;
  border-top: 1px solid #E8F5E8;
}

.view-all-btn, .mark-all-read-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s ease;
  font-family: '微软雅黑 Light', sans-serif;
}

.view-all-btn {
  background: #E8F5E8;
  color: #2E7D32;
  border: 1px solid #C8E6C9;
}

.view-all-btn:hover {
  background: #C8E6C9;
}

.mark-all-read-btn {
  background: linear-gradient(to right, #66BB6A, #43A047);
  color: white;
}

.mark-all-read-btn:hover:not(:disabled) {
  background: linear-gradient(to right, #558B2F, #388E3C);
  transform: translateY(-1px);
}

.mark-all-read-btn:disabled {
  background: #BDBDBD;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-panel {
    width: 320px;
    right: -50px;
  }
}
</style>
